package email;

import java.awt.*;
import java.awt.event.*;
import java.io.File;

import javax.mail.Address;
import javax.mail.Message;
import javax.swing.*;

// This class displays the dialog used for creating messages.
public class MessageDialog extends JDialog {
    
	private static final long serialVersionUID = 1L;
	// Dialog message identifiers.
    public static final int NEW = 0;
    public static final int REPLY = 1;
    public static final int FORWARD = 2;
    
    // Message from, to and subject text fields.
    private JTextField fromTextField, toTextField;
    private JTextField subjectTextField;
    
    // Message content text area.
    private JTextArea contentTextArea;
    
    //used to send emails
    private OutgoingMail sender;
    
    // Flag specifying whether or not dialog was cancelled.
    static boolean cancelled;
    
    // Constructor for dialog.
    public MessageDialog(Frame parent, int type, ReceivedMessage message){
    	setAlwaysOnTop(true);
    	//construct the outgoing mail object for use
    	sender = new OutgoingMail(EmailClient2.username, EmailClient2.password);
    	
    /* Set dialog title and get message's "to", "subject"
       and "content" values based on message type. */
        String to = "", subject = "", content = "";
        switch (type) {
            // Reply message.
            case REPLY:
                setTitle("Reply");
                to = message.getFrom();
                //set default subject
                subject = message.getSubject();
                if (subject != null && subject.length() > 0){
                	if (subject.length() >= 3){
                		String test = subject.substring(0, 3);
                		//if re is already there don't add it since it will cluter things up
                		if (test.compareToIgnoreCase("RE:") == 0){
                			//do nothing since the re is already there
                		}
                		//re not there so add it
                		else{
                			subject = "RE: " + subject;
                		}
                	}
                } 
                else{
                    subject = "RE:";
                }
                
                // Get message content and add "REPLIED TO" notation.
                content = "\n----------------- REPLIED TO MESSAGE -----------------\n";
                content += message.getBody();
                break;
            // Forward message.
            case FORWARD:
                setTitle("Forward Message");
                
                // Get message subject.
                subject = message.getSubject();
                if (subject != null && subject.length() > 0) {
                    subject = "FWD: " + subject;
                } else {
                    subject = "FWD:";
                }
                
                // Get message content and add "FORWARDED" notation.
                content = "\n----------------- FORWARDED MESSAGE -----------------\n";
                content += EmailClient2.getMessageBody(message);
                break;   
            // New message.
            default:
                setTitle("New Message");
        }
        
        // Handle closing events.
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                dispose();
                cancelled = true;
            }
        });
        
        // Setup fields panel.
        final JPanel fieldsPanel = new JPanel();
        GridBagConstraints constraints;
        GridBagLayout layout = new GridBagLayout();
        fieldsPanel.setLayout(layout);
        JLabel fromLabel = new JLabel("From:");
        constraints = new GridBagConstraints();
        constraints.anchor = GridBagConstraints.EAST;
        constraints.insets = new Insets(5, 5, 0, 0);
        layout.setConstraints(fromLabel, constraints);
        
        //set up from field
        fieldsPanel.add(fromLabel);
        fromTextField = new JTextField();
        constraints = new GridBagConstraints();
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.gridwidth = GridBagConstraints.REMAINDER;
        constraints.insets = new Insets(5, 5, 0, 0);
        fromTextField.setText(EmailClient2.username + "@gmail.com");
        fromTextField.setEditable(false);
        layout.setConstraints(fromTextField, constraints);
        fieldsPanel.add(fromTextField);
        
        //set up to field
        JLabel toLabel = new JLabel("To:");
        constraints = new GridBagConstraints();
        constraints.anchor = GridBagConstraints.EAST;
        constraints.insets = new Insets(5, 5, 0, 0);
        layout.setConstraints(toLabel, constraints);
        fieldsPanel.add(toLabel);
        toTextField = new JTextField(to);
        constraints = new GridBagConstraints();
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.gridwidth = GridBagConstraints.REMAINDER;
        constraints.insets = new Insets(5, 5, 0, 0);
        constraints.weightx = 1.0D;
        layout.setConstraints(toTextField, constraints);
        fieldsPanel.add(toTextField);
        
        //set up subject field
        JLabel subjectLabel = new JLabel("Subject:");
        constraints = new GridBagConstraints();
        constraints.insets = new Insets(5, 5, 5, 0);
        layout.setConstraints(subjectLabel, constraints);
        fieldsPanel.add(subjectLabel);
        subjectTextField = new JTextField(subject);
        constraints = new GridBagConstraints();
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.gridwidth = GridBagConstraints.REMAINDER;
        constraints.insets = new Insets(5, 5, 5, 0);
        layout.setConstraints(subjectTextField, constraints);
        fieldsPanel.add(subjectTextField);
        
        // Setup content panel.
        JScrollPane contentPanel = new JScrollPane();
        contentTextArea = new JTextArea(content, 10, 50);
        contentPanel.setViewportView(contentTextArea);
        
        // Setup buttons panel.
        JPanel buttonsPanel = new JPanel();
        JButton sendButton = new JButton("Send");
        sendButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //actionSend(e);
            	sendMessage();
            	dispose();
            }
        });
        buttonsPanel.add(sendButton);
        
        JButton cancelButton = new JButton("Cancel");
        cancelButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });
        buttonsPanel.add(cancelButton);
        
        /**
         * Attach button and listener here
         */
        JButton attach = new JButton("Attach");
        attach.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0) {
				JButton btn = (JButton) arg0.getSource();
				JFileChooser openFile = new JFileChooser();
				JButton src = (JButton)arg0.getSource();
				int result = openFile.showOpenDialog(btn);
				if(result == JFileChooser.CANCEL_OPTION){
					openFile.setVisible(false);
				}
				if(result == JFileChooser.APPROVE_OPTION){
					File file = openFile.getSelectedFile();
					
					//try to add an attachment to the message
					try{
						sender.addAttachment(file);
					}
					//if an IllegalArgumentException is thrown the file failed the file filter
					catch (IllegalArgumentException e){
						JOptionPane.showMessageDialog(contentTextArea, "Selected file type is not allowed!");
						return;
					}
					
					if(sender.attachments.size() >= 1){
						JOptionPane.showMessageDialog(btn, "Attachment(s) Added Successfully");
						return;
					}
					else if(sender.attachments.size() < 1)
						JOptionPane.showMessageDialog(btn, "Attachment(s) addition failed! Please try again.");
				}
			}
        	
        });
        buttonsPanel.add(attach);
        
        // Add panels to display.
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(fieldsPanel, BorderLayout.NORTH);
        getContentPane().add(contentPanel, BorderLayout.CENTER);
        getContentPane().add(buttonsPanel, BorderLayout.SOUTH);
        
        // Size dialog to components.
        pack();
        
        // Center dialog over application.
        setLocationRelativeTo(parent);
    }
    
    /**
     * Sends the message
     * @return true if the user follows through with sending it (if subject or body is blank the user can 
     * abort the send) false if not.
     */
    private boolean sendMessage(){
    	String to = toTextField.getText();
    	String subject = subjectTextField.getText();
    	String body = contentTextArea.getText();
    	
    	if (to.equals("") || to == null){
    		JOptionPane.showMessageDialog(contentTextArea, "No recipient specified!");
    		return false;
    	}
    	
    	try{
    		sender.sendMessage(to, subject, body);
    	}
    	catch (Exception e){
    		e.printStackTrace();
    		JOptionPane.showMessageDialog(contentTextArea, "Sending failed please try again!");
    		return false;
    	}
    	
    	return true;
    }
    
}